package com.example.demo.export.exportInterfaceTask;

import com.example.demo.export.entity.Person;
import com.example.demo.export.exportInterface.ExportInterface;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 类描述:
 *
 * @author jianweiwang
 * @version v1.0
 * @link wjw@choicesoft.com.cn
 * @date 2018/12/11 15:30
 **/
public class ExportInterfaceTask implements ExportInterface {
    @Override
    public HSSFWorkbook createBook(List<Person> data, List<Map<String, Object>> columnsData) {
        List<String> lists = columnsData.stream().map(map ->map.get("columnName").toString()).collect(Collectors.toList());
        List<Map<String, Object>> list = new ArrayList<>();
        for (Person person : data) {
            BeanMap beanMap = BeanMap.create(person);
            Map<String,Object> map = new HashMap<>();
            for (Map<String, Object> datum : columnsData) {
                String column = datum.get("column").toString();
                String columnName = datum.get("columnName").toString();
                Object value = beanMap.get(column);
                map.put(columnName,value);
            }
            list.add(map);
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell;
        for (int i = 0; i < lists.size(); i++) {
            cell = row.createCell(i);
            cell.setCellValue(lists.get(i));
        }
        for (int i = 0; i < list.size(); i++) {
            Map<String,Object> map = list.get(i);
            row = sheet.createRow(i+1);
            for (int j = 0; j < lists.size(); j++) {
                cell = row.createCell(j);
                cell.setCellValue(map.get(lists.get(j)).toString());
            }
        }
        return wb;
    }
}
